package com.txw.javaCore.server.config;

import com.txw.javaCore.server.session.SessonConditionRedis;
import com.txw.javaCore.server.shiro.UserRealm;
import org.apache.shiro.mgt.SecurityManager;
import org.apache.shiro.spring.LifecycleBeanPostProcessor;
import org.apache.shiro.spring.security.interceptor.AuthorizationAttributeSourceAdvisor;
import org.apache.shiro.spring.web.ShiroFilterFactoryBean;
import org.apache.shiro.web.mgt.DefaultWebSecurityManager;
import org.apache.shiro.web.session.mgt.DefaultWebSessionManager;
import org.crazycake.shiro.RedisCacheManager;
import org.crazycake.shiro.RedisManager;
import org.crazycake.shiro.RedisSessionDAO;
import org.springframework.context.EnvironmentAware;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Conditional;
import org.springframework.context.annotation.Configuration;
import org.springframework.core.env.Environment;

import java.util.LinkedHashMap;
import java.util.Map;

/**
 * @PROJECT_NAME: JavaCoreB2
 * @DESCRIPTION: 集群部署模式下Session共享优化案例
 * @Author: 涂玄武
 * @DATE: 2021/2/24 15:39
 */
@Configuration
@Conditional(SessonConditionRedis.class)
public class ShiroRedisConfig implements EnvironmentAware {

    private Environment env;

    @Override
    public void setEnvironment(Environment environment) {
        this.env = environment;
    }

    /**
     * 安全器管理-管理所有的subject
     * @param userRealm
     * @return
     */
    @Bean
    public SecurityManager securityManager(UserRealm userRealm){
        DefaultWebSecurityManager securityManager=new DefaultWebSecurityManager();
        securityManager.setRealm(userRealm);
        securityManager.setRememberMeManager(null);

        //自定义缓存管理器（redis）
        securityManager.setCacheManager(cacheManager());

        //自定义存储session的管理器（redis）
        securityManager.setSessionManager(sessionManager());

        return securityManager;
    }

    /**
     * 自定义缓存管理器
     * @return
     */
    @Bean
    public RedisCacheManager cacheManager(){
        RedisCacheManager redisCacheManager = new RedisCacheManager();
        redisCacheManager.setRedisManager(redisManager());
        return redisCacheManager;
    }

    @Bean
    public RedisManager redisManager(){
        RedisManager redisManager = new RedisManager();
        redisManager.setHost(env.getProperty("spring.redis.host"));
        redisManager.setPort(env.getProperty("spring.redis.port",Integer.class));
        redisManager.setPassword(env.getProperty("spring.redis.password"));
        //连接超时
        redisManager.setTimeout(env.getProperty("spring.redis.timeout",Integer.class));
        //缓存key的有效时间
        redisManager.setExpire(env.getProperty("spring.redis.expire",Integer.class));
        return redisManager;
    }

    /**
     * 自定义存储session的管理器
     * @return
     */
    @Bean
    public DefaultWebSessionManager sessionManager(){
        DefaultWebSessionManager sessionManager = new DefaultWebSessionManager();
        //SessionDAO可以理解为真正存储到缓存的session对应key的管理
        sessionManager.setSessionDAO(sessionDAO());
        return sessionManager;
    }

    @Bean
    public RedisSessionDAO sessionDAO(){
        RedisSessionDAO redisSessionDAO = new RedisSessionDAO();
        redisSessionDAO.setRedisManager(redisManager());
        //设置sessionID存储到redis的时候key的前缀/配置
        redisSessionDAO.setKeyPrefix("shiro_redis_sessionKey_v1:");
        return redisSessionDAO;
    }

    //过滤链配置
    @Bean("shiroFilter")
    public ShiroFilterFactoryBean shiroFilter(SecurityManager securityManager){
        ShiroFilterFactoryBean shiroFilter=new ShiroFilterFactoryBean();
        shiroFilter.setSecurityManager(securityManager);

        //设定用户没有登录认证时的跳转链接、没有授权时的跳转链接
        shiroFilter.setLoginUrl("/login.html");
        shiroFilter.setUnauthorizedUrl("/login.html");

        //过滤器链配置
        Map<String, String> filterMap = new LinkedHashMap();
        filterMap.put("/", "anon");
        filterMap.put("/web/**", "anon");

        filterMap.put("/swagger/**", "anon");
        filterMap.put("/swagger-ui.html", "anon");
        filterMap.put("/webjars/**", "anon");
        filterMap.put("/swagger-resources/**", "anon");

        filterMap.put("/statics/**", "anon");
        filterMap.put("/login.html", "anon");
        filterMap.put("/register.html", "anon");
        filterMap.put("/sys/login", "anon");
        filterMap.put("/favicon.ico", "anon");
        filterMap.put("/captcha.jpg", "anon");
        filterMap.put("/base/**", "anon");

        filterMap.put("/image/**", "anon");
        filterMap.put("/ws/**", "anon");

        //filterMap.put("/**","authc");
        filterMap.put("/**","anon");

        shiroFilter.setFilterChainDefinitionMap(filterMap);
        return shiroFilter;
    }

    //关于Shiro的Bean生命周期的管理
    @Bean("lifecycleBeanPostProcessor")
    public LifecycleBeanPostProcessor lifecycleBeanPostProcessor(){
        return new LifecycleBeanPostProcessor();
    }

    @Bean
    public AuthorizationAttributeSourceAdvisor authorizationAttributeSourceAdvisor(SecurityManager securityManager){
        AuthorizationAttributeSourceAdvisor advisor=new AuthorizationAttributeSourceAdvisor();
        advisor.setSecurityManager(securityManager);
        return advisor;
    }
}
